package com.woniuxy.hotel.user.service.serviceimpl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.woniuxy.hotel.user.pojo.User;
import com.woniuxy.hotel.user.service.MailService;

@Service
@Scope("prototype")
public class MailServiceImpl implements MailService {
	
	private final static Logger log = LoggerFactory.getLogger(MailServiceImpl.class);

	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private TemplateEngine templateEngine;
	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;

	@Value("${spring.mail.username}")
	private String from;

	@Override
	public String sendSimpleMail(User user, String subject) {
		Map<String, Object> info = new HashMap<>();
		info.put("account", user.getAccount());
		String code = "";
		for (int i = 0; i < 6; i++) {
			code += (int) (Math.random() * 10);
		}
		System.out.println(code);
		info.put("code", code);
		redisTemplate.opsForValue().set(user.getAccount(), code, 240, TimeUnit.SECONDS);
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(from);
			helper.setTo(user.getEmail());
			helper.setSubject(subject);
			Context context = new Context();
			context.setVariables(info);
			String emailContent = templateEngine.process("/email", context); //指定模板路径
			helper.setText(emailContent, true);// 重点，默认为false，显示原始html代码，无效果
			mailSender.send(mimeMessage);
		} catch (MessagingException e) {
			log.error("模板邮件发送失败->message:{}",e.getMessage());
            throw new RuntimeException("件发送失败");
		}
		return "邮件 已发送至"+user.getEmail()+"邮箱";
	}
}
